package com.hefan.robot.service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.hefan.common.ons.TopicRegistry;
import com.hefan.common.ons.service.ONSProducer;
import com.hefan.common.util.MapUtils;
import com.hefan.live.bean.LivingRoomInfoVo;
import com.hefan.live.bean.RobotListenerVo;
import com.hefan.live.itf.LivingRedisOptService;
import com.hefan.live.itf.RoomEnterExitOptService;
import com.hefan.robot.common.util.DateUtils;
import com.hefan.robot.common.util.RandomUtil;
import com.hefan.robot.configCenter.RobotConfigCenter;
import com.hefan.robot.itf.LeftRoomTimer;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import java.util.Map;

/**
 * 定时监测直播间新进观众情况，10分钟内无新观众进入，则减少机器人
 * Created by nigle on 2016/12/9.
 */
@Path("/robot")
@Component("leftRoomTimer")
public class LeftRoomTimerImpl implements LeftRoomTimer{

    @Resource
    LivingRedisOptService livingRedisOptService;
    @Resource
    RoomEnterExitOptService roomEnterExitOptService;
    @Resource
    private RobotConfigCenter robotConfigCenter;
    @Resource
    ONSProducer onsProducer;

    private Logger logger = LoggerFactory.getLogger(ExtraRobotServiceImpl.class);

    @GET
    @Path("/leftTimer")
    @Override
    @Produces({ MediaType.APPLICATION_JSON })
    @Consumes({ MediaType.APPLICATION_JSON })
    public void leftTimer() {
        logger.info("扫描正在直播的直播间，无新观众则减少机器人，任务开始");
        Map<String,String> livingMap = livingRedisOptService.getAllLivingInfo_Hash();
        if ( null != livingMap && livingMap.isEmpty()){
            logger.info("没有正在进行的直播");
            return;
        }
        Map<String,String> propty = robotConfigCenter.getPublicConfig();
        //最大相隔时长
        long leftTime = MapUtils.getLongValue(propty,"robot.left.time",600000);
        for (Map.Entry<String, String> entry : livingMap.entrySet()) {
            LivingRoomInfoVo vo = JSON.parseObject(entry.getValue(), LivingRoomInfoVo.class);
            String lastTimeStr = livingRedisOptService.getLastJoinTime(vo.getLiveUuid());
            logger.info("anchId:{},lastTimeStr:{}",entry.getKey() ,DateUtils.stampToDate(lastTimeStr));
            if (StringUtils.isNotBlank(lastTimeStr)) {
                long lastTime = Long.valueOf(lastTimeStr);
                long now = System.currentTimeMillis();
                logger.info("主播ID：{}上次进入房间时间：{}",entry.getKey(),DateUtils.stampToDate(lastTimeStr));
                if (now - lastTime > leftTime) {
                    //减少机器人和更新lastTime
                    LivingRoomInfoVo livingRoomInfoVo;
                    String liveInfo = livingRedisOptService.getLivingInfo_Hash(entry.getKey());
                    if (null == liveInfo || StringUtils.isBlank(liveInfo)) {
                        logger.error("主播：{}的直播信息获取失败", entry.getKey());
                        continue;
                    }
                    livingRoomInfoVo = JSONObject.parseObject(liveInfo, LivingRoomInfoVo.class);
                    if (null == livingRoomInfoVo) {
                        logger.error("主播：{}的直播信息解析失败",entry.getKey());
                    }
                    clearRobot(livingRoomInfoVo);
                }
            }else {
                logger.error("主播：{}的观众最新进入时间获取失败",entry.getKey());
                continue;
            }
        }
        logger.info("扫描正在直播的直播间，无新观众则减少机器人，任务结束");
    }

    /**
     * 减少机器人
     * 更新lastTime
     */
    private void clearRobot(LivingRoomInfoVo vo) {

        //获取直播间机器人数
        long robotCount = livingRedisOptService.getLivingRobotCount(vo.getUserId());
        if (robotCount > 20) {
            int robotSuccessCount = 0;
            Map<String,String> propty = robotConfigCenter.getPublicConfig();
            int countBack = MapUtils.getIntValue(propty, "robot.back.count.speed.min", 200);
            int robotDelay = 60*1000/countBack;
            double reduce = Double.valueOf(MapUtils.getStrValue(propty,"robot.reduce.num","0.3"));
            String onsEnv = MapUtils.getStrValue(propty, "ons.env", "");
            RobotListenerVo rvo = new RobotListenerVo();
            rvo.setAnchId(vo.getUserId());
            rvo.setLiveUuid(vo.getLiveUuid());
            rvo.setChatRoomId(vo.getChatRoomId());
            rvo.setInOrOut(0);
            int flag = RandomUtil.getRandom(1000, 5000);
            double count = Math.floor(robotCount * reduce);
            for (int i = 0; i < count ; i++) {
                com.hefan.common.ons.bean.Message message = new com.hefan.common.ons.bean.Message();
                rvo.setInfo("机器人消费过滤主播ID：" + vo.getUserId() + "无新减少机器人任务ID：" + flag + "--执行总次数：" + count + "，本次第" + i + "个");
                message.put("vo", JSON.toJSONString(rvo));
                message.setTopic(TopicRegistry.HEFAN_ROBOT_ENTER_EXIT_DELAY);
                message.setTag(onsEnv);
                onsProducer.sendDelayMsg(message, robotDelay * i);
                logger.info("发送MQ：{}直播间减少机器人(无新减少触发)第{}个，延时{}毫秒", vo.getUserId(), robotSuccessCount , robotDelay);
                robotSuccessCount++;
            }
            logger.info("机器人消费过滤{}的直播间，无新减少，原机器人数量：{}，预计移除机器人数量：{}， 发送离开任务数：{}", vo.getUserId(), robotCount, Math.floor(robotCount * reduce), robotSuccessCount);
        }
        //更新最后一次进入时间
        try {
            livingRedisOptService.addLastJoinTime(vo.getLiveUuid());
        } catch (Exception e) {
            e.printStackTrace();
            logger.info("更新直播间最后进入时间失败");
        }
    }
}